/********************************************************************************
  * @file    commandlineedit.cpp
  * @author  Lun Li
  * @version V2.2.0
  * @date    2022.7.8
  * @brief   This file provides all CommandLineEdit functions.
  *******************************************************************************/

#include "commandlineedit.h"

#include <QKeyEvent>

CommandLineEdit::CommandLineEdit(QWidget *parent)
    : QLineEdit(parent)
{
    connect(this, &QLineEdit::textEdited, this, [&](const QString &text) {
        ptr = commandList.length();
        currentCommand = text;
    });
}

void CommandLineEdit::addCommand(const QString &command)
{
    if (commandList.length() > 1024) { // 最多保存1024个命令
        commandList.dequeue();
    }
    commandList.enqueue(command);
    ptr = commandList.length();
}

void CommandLineEdit::clear()
{
    currentCommand.clear();
    QLineEdit::clear();
}

void CommandLineEdit::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Up) { // 按上键时显示上一个命令
        if (ptr > 0 && ptr <= commandList.length()) {
            setText(commandList.at(--ptr));
        }
    } else if (event->key() == Qt::Key_Down) { // 按下键时显示下一个命令
        if (ptr >= 0 && ptr < commandList.length() - 1) {
            setText(commandList.at(++ptr));
        } else if (ptr == commandList.length() - 1) {
            setText(currentCommand);
            ++ptr;
        }
    }
    QLineEdit::keyPressEvent(event);
}
